package com.banzhi.shop.activity;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.banzhi.shop.MyApp;
import com.banzhi.shop.R;
import com.banzhi.shop.base.BaseActivity;
import com.banzhi.shop.entity.Setting.Setting_Data;
import com.banzhi.shop.model.CallBack.SettingCallBack;
import com.banzhi.shop.model.ISettingModel;
import com.banzhi.shop.model.Impl.SettingImpl;
import com.banzhi.shop.service.DownloadService;
import com.banzhi.shop.utils.ASUtils;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.TemplatePopupwindowUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.utils.Translucent;

import org.json.JSONObject;

/**
 * 设置
 */
public class SettingActivity extends BaseActivity implements View.OnClickListener, SettingCallBack {
    /**
     * 退出
     */
    private ImageView ivback;
    /**
     * 个人中心
     */
    private LinearLayout llpersondetail;
    /**
     * 安全中心
     */
    private LinearLayout llsafe;
    /**
     * 关于半职
     */
    private LinearLayout llbanzhi;
    /**
     * 检查更新
     */
    private LinearLayout llnewcheck;
    /**
     * 登出
     */
    private Button btn_loginout;
    /**
     * 版本号
     */
    private TextView tvbanben;
    private ISettingModel model;
    /**
     * 客服服务
     */
    private LinearLayout llservice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        Translucent.setTranslucent(this);
        setinits();
        setListeners();
        model = new SettingImpl();
    }

    private void setinits() {
        ivback = (ImageView) findViewById(R.id.iv_back);
        llpersondetail = (LinearLayout) findViewById(R.id.ll_persondetail);
        llservice = (LinearLayout) findViewById(R.id.ll_service);
        llsafe = (LinearLayout) findViewById(R.id.ll_safe);
        llbanzhi = (LinearLayout) findViewById(R.id.ll_banzhi);
        llnewcheck = (LinearLayout) findViewById(R.id.ll_newcheck);
        btn_loginout = (Button) findViewById(R.id.btn_logout);
        tvbanben = (TextView) findViewById(R.id.tv_banben);
        tvbanben.setText(ASUtils.getVersionName(this));
    }

    private void setListeners() {
        ivback.setOnClickListener(this);
        llpersondetail.setOnClickListener(this);
        llsafe.setOnClickListener(this);
        btn_loginout.setOnClickListener(this);
        llbanzhi.setOnClickListener(this);
        llnewcheck.setOnClickListener(this);
        llservice.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_persondetail:
                Intent PDintent = new Intent(this, PersonDetailActivity.class);
                startActivity(PDintent);
                break;
            case R.id.ll_safe:
                Intent safeintent = new Intent(this, SafeCenterActivity.class);
                startActivity(safeintent);
                break;
            case R.id.btn_logout:
                Intent intent = new Intent(this, NewLoginActivity.class);
                this.startActivity(intent);
                SharedPreferences.Editor editor = MyApp.loginMessage.edit();
                editor.putString("token", "");
                editor.putString("personNickname", "");
                editor.putString("personAvatar", "");
                editor.putString("personBirth", "");
                editor.putString("personGender", "");
                editor.putString("shopname", "");
                editor.putString("shoplogo", "");
                editor.putString("shopimg", "");
                editor.putString("shopDescription", "");
                editor.putString("recommendName", "");
                editor.putString("isagent","");
                editor.apply();
                finishAllActivity();
                break;
            case R.id.ll_banzhi:
                Intent ABintent = new Intent(this, AboutBanzhiActivity.class);
                startActivity(ABintent);
                break;
            case R.id.ll_newcheck:
                LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                model.getData(this);
                break;
            case R.id.ll_service:
                Intent intent1 = new Intent(this, MyServiceActivity.class);
                startActivity(intent1);
                break;
        }
    }

    private PopupWindow popWindow;
    private Setting_Data setting;

    /**
     * 版本更新
     */
    private void popupwindow(final String str) {
        View contentView = LayoutInflater.from(this).inflate(R.layout.popupwindow_updating, null);
        popWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popWindow.setContentView(contentView);
        popWindow.setAnimationStyle(R.style.AnimBottom);

        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);// 设置允许在外点击消失
        //设置各个控件的点击响应
        TextView tv1 = (TextView) contentView.findViewById(R.id.tv_know);
        TextView tv2 = (TextView) contentView.findViewById(R.id.tv_copy);
        RelativeLayout rlbackground = (RelativeLayout) contentView.findViewById(R.id.rl_background);
        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);
        rlbackground.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        tv1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        tv2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1000);
                } else {
                    MyApp.IsCheck = true;
                    Intent inetent = new Intent(SettingActivity.this, DownloadService.class);
                    inetent.putExtra("downloadUrl", str);
                    startService(inetent);
                    ToastUtils.makeToastLong("正在下载更新中，请稍后");
                    popWindow.dismiss();
                }
            }
        });
        //显示PopupWindow
        View rootview = LayoutInflater.from(this).inflate(R.layout.activity_main, null);
        popWindow.showAtLocation(rootview, Gravity.CENTER, 0, 0);


    }

    /**
     * @param object 成功
     */
    @Override
    public void onsettingSuccess(Object object) {
        setting = (Setting_Data) object;
        if (!ASUtils.getVersionName(this).equals(setting.getAPP_VERSION())) {
            if (!MyApp.IsCheck) {
                popupwindow(setting.getANDROID_URL());
            } else {
                ToastUtils.makeToastShort("正在更新中");
            }
        } else {
            ToastUtils.makeToastShort("已是最新版本了");
        }
//        if (!ASUtils.getVersionName(this).equals(setting.getAPP_VERSION())) {
//            if (!MyApp.IsCheck) {
//                popupwindow(setting.getANDROID_URL());
//            } else {
//                ToastUtils.makeToastShort("正在更新中");
//            }
//        } else {
//            ToastUtils.makeToastShort("已是最新版本了");
//        }

    }


    /**
     * @param object 失败
     */
    @Override
    public void onsettingError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    //Android6.0申请权限的回调方法
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case 1000:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    MyApp.IsCheck = true;
                    Intent inetent = new Intent(SettingActivity.this, DownloadService.class);
                    inetent.putExtra("downloadUrl", setting.getANDROID_URL());
                    startService(inetent);
                    ToastUtils.makeToastLong("正在下载更新中，请稍后");
                    popWindow.dismiss();
                } else {
                    TemplatePopupwindowUtils.showPermissionsPopupWindow(SettingActivity.this, "为了能够正常更新版本", "请开启读写手机存储权限");
                }
        }
    }
}
